/*
 * 文件名               :  ByteArrayOutputThread.java
 * 用途                    :  负责向流写入byte数组
 * 最后修改日期:  $LastChangedDate: 2009-10-17 03:54:49 +0000 (Sat, 17 Oct 2009) $
 * 最后修改者     :  $LastChangedBy: wendal1985@gmail.com $
 * 创建者               :  Wendal Chen <wendal1985@gmail.com>
 */
package com.wendal.java.preproxy.thread;

import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;
import java.util.Queue;
import java.util.concurrent.LinkedBlockingQueue;

public class ByteArrayOutputThread extends Thread {
	private Socket socket;
	
	private OutputStream os;
	
	private Queue<byte[]> queue;
	
//	private Log log = LogFactory.getLog(getClass());
	
	private boolean flag;
	
	public ByteArrayOutputThread(Socket socket) throws IOException {
		super("ByteArrayOutputThread_"+System.currentTimeMillis());
		this.socket = socket;
		this.os = socket.getOutputStream();
		queue = new LinkedBlockingQueue<byte[]>();
	}
	
	public void addData(byte[] data){
		synchronized (queue) {
			queue.add(data);
		}
	}
	
	@Override
	public void run() {
		byte [] data ;
		int idle = 0;
		while(socket.isConnected() && ! socket.isOutputShutdown()){
			if(flag) break;
			synchronized (queue) {
				data = queue.poll();
			}
			if(data == null){
				try {
					Thread.sleep(100);
					idle += 100;
					if(idle > 10 * 1000){//连续10秒收不到数据的话,就结束线程!
						break;
					}
				} catch (InterruptedException e) {
					System.out.println("A thread get some exception: " + e.getMessage());
					break;
				}
			}else{
				try {
					os.write(data);
					os.flush();
					idle= 0;
				} catch (IOException e) {
					System.out.println("A thread get some exception: " + e.getMessage());
					break;
				}
			}
		}
//		log.info("线程终止... "+this);
	}
	
	public void setFlag(boolean flag) {
		this.flag = flag;
	}
}
